import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'address_model.dart';

class AddressManager {
  static List<AddressProvince> _provinces = [];
  static Map<String, AddressProvince> _provinceMap = {};
  static  Map<String, AddressCity> _cityMap = {};
  static  Map<String, AddressDistrict> _districtMap = {};

  static Future<List<AddressProvince>> loadAddressData () async {
    // if (_provinces.isNotEmpty) {
    //   return _provinces;
    // }
    var address = await rootBundle.loadString('assets/jsonfile/address.json');
    var data = json.decode(address);
    List <AddressProvince> provinces = [];
    if (data is List) {
      for (var v in data) {
        var province = AddressProvince.fromJson(v, cityMap: _cityMap, districtMap: _districtMap);
        _provinceMap[province.provinceid] = province;
        provinces.add(province);
      }
      _provinces = provinces;
      return _provinces;
    }
    return <AddressProvince>[];
  }

  static Future<List<AddressInternational>> loadInternationalData () async {

    var address = await rootBundle.loadString('assets/jsonfile/country.json');
    List data = json.decode(address);
    List <AddressInternational> international = [];
    if (data is List) {
      for (var v in data) {
        var internationalData = AddressInternational.fromJson(v);
        international.add(internationalData);
      }
    }
    return international;
  }

  static Future<AddressProvince?> getProvince(String provinceId) async {
    if (_provinceMap.isEmpty) {
      var provinces = await loadAddressData();
      if (provinces.isNotEmpty) {
        return _provinceMap[provinceId];
      }
      return null;
    } else {
      return _provinceMap[provinceId];
    }
  }

  static Future<AddressCity?> getCity(String cityId) async {
    if (_cityMap.isEmpty) {
      var provinces = await loadAddressData();
      if (provinces.isNotEmpty) {
        return _cityMap[cityId];
      }
      return null;
    } else {
      return _cityMap[cityId];
    }
  }

  static Future<AddressDistrict?> getDistrict(BuildContext context, String districtId) async {
    if (_districtMap.isEmpty) {
      var provinces = await loadAddressData();
      if (provinces.isNotEmpty) {
        return _districtMap[districtId];
      }
      return null;
    } else {
      return _districtMap[districtId];
    }
  }
}
